package com.hyt.it.ogt.opertaion.track.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.async.AsyncWebRequest;
import org.springframework.web.context.request.async.WebAsyncUtils;

import static com.hyt.it.ogt.opertaion.track.constants.OperationTrackConstants.REMOTE_USER;


/**
 * @author 朱振宇
 * @since 2022/10/13
 */
@Slf4j
public class WebRequestUtil {

    private final static NonWebRequestAttributes nonWebRequestAttributes = new NonWebRequestAttributes();

    public static RequestAttributes getRequestAttributesSafely(){
        RequestAttributes requestAttributes;
        try{
            requestAttributes = RequestContextHolder.currentRequestAttributes();
        }catch (IllegalStateException e){
            return nonWebRequestAttributes;
        }
        return requestAttributes;
    }

    /**
     * 会话中匹配角色
     * @return
     */
    public static String getAuthUser() {
        try {
            if(RequestContextHolder.getRequestAttributes() != null) {
                RequestAttributes requestAttributes =  RequestContextHolder.currentRequestAttributes();
                if(requestAttributes != null) {
                    String remoteUser = ((ServletRequestAttributes) requestAttributes).getRequest().getHeader(REMOTE_USER);
                    if(!com.hyt.core.util.StringUtils.isEmpty(remoteUser)) {
                        return remoteUser;
                    }
                    AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(((ServletRequestAttributes) requestAttributes).getRequest(), ((ServletRequestAttributes) requestAttributes).getResponse());
                    return asyncWebRequest.getRemoteUser();
                }
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        return null;
    }
}
